// app/service/collection_record_service.js
'use strict';

const Service = require('egg').Service;

class CollectionRecordService extends Service {
  // 获取催款记录列表
  async getRecords(query) {
    const { ctx } = this;
    const { page = 1, limit = 20, ...otherQuery } = query;
    
    const offset = (parseInt(page) - 1) * parseInt(limit);
    
    const { rows, count } = await ctx.model.CollectionRecordModel.findAndCountAll({
      where: otherQuery,
      limit: parseInt(limit),
      offset,
      order: [['collectionDate', 'DESC']]
    });
    
    return {
      list: rows,
      total: count,
      page: parseInt(page),
      limit: parseInt(limit)
    };
  }
  
  // 根据ID获取催款记录
  async getRecordById(id) {
    const { ctx } = this;
    return await ctx.model.CollectionRecordModel.findByPk(id, {
      include: [{
        model: ctx.model.SalesOrderModel,
        as: 'order',
        include: [{
          model: ctx.model.CustomerModel,
          as: 'customer',
          attributes: ['name']
        }],
        attributes: ['id', 'orderNo', 'orderAmount', 'orderDate']
      }]
    });
  }
  
  // 创建催款记录
  async createRecord(recordData) {
    const { ctx } = this;
    return await ctx.model.CollectionRecordModel.create(recordData);
  }
  
  // 更新催款记录
  async updateRecord(id, recordData) {
    const { ctx } = this;
    const record = await ctx.model.CollectionRecordModel.findByPk(id);
    if (!record) {
      throw new Error('催款记录不存在');
    }
    return await record.update(recordData);
  }
  
  // 删除催款记录
  async deleteRecord(id) {
    const { ctx } = this;
    const record = await ctx.model.CollectionRecordModel.findByPk(id);
    if (!record) {
      throw new Error('催款记录不存在');
    }
    return await record.destroy();
  }
  
  // 根据销售订单ID获取催款记录
  async getRecordsByOrderId(orderId) {
    const { ctx } = this;
    return await ctx.model.CollectionRecordModel.findAll({
      where: {
        salesOrderId: orderId
      },
      order: [['collectionDate', 'DESC']],
      include: [{
        model: ctx.model.SalesOrderModel,
        as: 'order',
        include: [{
          model: ctx.model.CustomerModel,
          as: 'customer',
          attributes: ['name']
        }],
        attributes: ['id', 'orderNo', 'orderAmount', 'orderDate']
      }]
    });
  }
}

module.exports = CollectionRecordService;